import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:management/model/open_gate_record_model.dart';

///开闸记录
class OpenGateRecord extends StatefulWidget {
  final List<GateRecordModel>? recordLists;

  const OpenGateRecord({Key? key, this.recordLists}) : super(key: key);

  @override
  _OpenGateRecordState createState() => _OpenGateRecordState();
}

class _OpenGateRecordState extends State<OpenGateRecord> {
   List<GateRecordModel>? lists;
  var _rowsPerPage = 10;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

  @override
  Widget build(BuildContext context) {
    // lists = ModalRoute.of(context).settings.arguments;
    lists = widget.recordLists;
    // lists.forEach((element) {
    //   MyLog.i("${element.toMap()}");
    // });

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          iconSize: 35,
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          "开闸记录",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
        centerTitle: false,
      ),
      body: lists == null
          ? Center(
              child: Text(
                "没有记录",
                style: TextStyle(fontSize: 25),
              ),
            )
          // : _buildBody(),
          : _buildPaginateDataTable(),
    );
  }

  Widget _buildBody() {
    return Container(
      padding: EdgeInsets.only(top: 30),
      child: Column(
        children: [
          Container(
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 30),
                  child: Text(
                    "控制方式",
                    style: TextStyle(fontSize: 25),
                  ),
                ),
                Padding(
                  child: Text(
                    "时间",
                    style: TextStyle(fontSize: 25),
                  ),
                  padding: EdgeInsets.only(left: 170),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 275),
                  child: Text(
                    "通道名称",
                    style: TextStyle(fontSize: 25),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 260),
                  child: Text(
                    "设备MAC",
                    style: TextStyle(fontSize: 25),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 252),
                  child: Text(
                    "通行人员",
                    style: TextStyle(fontSize: 25),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 235),
                  child: Text(
                    "放行人员",
                    style: TextStyle(fontSize: 25),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemBuilder: _buildListItem,
              itemCount: lists!.length,
            ),
          )
        ],
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    var gateRecordModel = lists![lists!.length - 1 - index];
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: Card(
        elevation: 3,
        shadowColor: Colors.indigo,
        child: InkWell(
          child: Container(
            height: 80,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(
                  // color: Colors.indigo,
                  child: gateRecordModel.controlType == 1
                      ? Icon(
                          Icons.mic,
                          size: 30,
                        )
                      : gateRecordModel.controlType == null
                          ? Icon(
                              Icons.fiber_manual_record_outlined,
                              size: 30,
                            )
                          : Icon(
                              Icons.fiber_manual_record_outlined,
                              size: 30,
                            ),
                ),
                Container(
                  width: 260,
                  alignment: Alignment.center,
                  color: Colors.green,
                  child: Text(
                    "${gateRecordModel.time}",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
                Container(
                  width: 220,
                  alignment: Alignment.center,
                  color: Colors.yellow,
                  child: Text(
                    gateRecordModel.gateName == null
                        ? "无记录" //
                        : "${gateRecordModel.gateName}",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
                Container(
                  width: 300,
                  color: Colors.greenAccent,
                  alignment: Alignment.center,
                  child: Text(
                    "${gateRecordModel.gateMac}",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
                Container(
                  width: 200,
                  alignment: Alignment.center,
                  color: Colors.lightBlue,
                  child: Text(
                    "${gateRecordModel.passerby}",
                    // "易烊千玺",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
                Container(
                  width: 260,
                  color: Colors.yellow,
                  alignment: Alignment.center,
                  child: Text(
                    "${gateRecordModel.operator}",

                    /// "abcdefghijklmnopqrstuvwxyz",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
              ],
            ),
          ),
          onLongPress: () {
            if (SpUtil.getString("userName") == "admin") {
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: Text("提示"),
                  content: Text(
                    "删除该条记录",
                    style: TextStyle(color: Colors.red),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () {
                        GateRecordProvider.instance.delete(
                          GateRecordModel(
                            time: gateRecordModel.time,
                            gateMac: gateRecordModel.gateMac,
                            passerby: gateRecordModel.passerby,
                            operator: gateRecordModel.operator,
                          ),
                        );
                        GateRecordProvider.instance.close();
                        setState(() {
                          lists!.removeAt(index);
                        });
                        Navigator.of(context).pop();
                      },
                      child: Text("确定"),
                    ),
                    TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text("取消"),
                    ),
                  ],
                ),
              );
            }
          },
        ),
      ),
    );
  }

  var _sortAscending = false;

  Widget _buildPaginateDataTable() {
    return SingleChildScrollView(
      child: PaginatedDataTable(
        header: Text(""),
        actions: [
          if (SpUtil.getString("userName") == "admin")
            IconButton(
                onPressed: () {
                  List<GateRecordModel> selectedLists = [];

                  lists!.forEach((element) async {
                    if (element.selected!) {
                      selectedLists.add(element);
                      await GateRecordProvider.instance.delete(element);
                    }
                  });
                  GateRecordProvider.instance.close();
                  selectedLists.forEach((element) {
                    lists!.remove(element);
                  });
                  setState(() {});
                },
                icon: Icon(
                  Icons.delete,
                  size: 35,
                ))
        ],
        columnSpacing: 0,
        horizontalMargin: (MediaQuery.of(context).size.width - 1800) / 2,
        dataRowHeight: 80,
        rowsPerPage: _rowsPerPage,
        onRowsPerPageChanged: (v) {
          setState(() {
            _rowsPerPage = v!;
          });
        },
        sortColumnIndex: 1,
        sortAscending: _sortAscending,
        onSelectAll: (all) {
          setState(() {
            lists!.forEach((element) {
              element.selected = all;
            });
          });
        },
        columns: [
          DataColumn(
            label: Container(
              width: 300,
              alignment: Alignment.center,
              child: Text(
                "控制方式",
                style: TextStyle(fontSize: 25),
              ),
            ),
          ),
          DataColumn(
              label: Container(
                width: 300,
                alignment: Alignment.center,
                child: Text(
                  "时间",
                  style: TextStyle(fontSize: 25),
                ),
              ),
              onSort: (index, sortAscending) {
                setState(() {
                  _sortAscending = sortAscending;
                  if (sortAscending) {
                    lists!.sort((a, b) => a.time!.compareTo(b.time!));
                  } else {
                    lists!.sort((a, b) => b.time!.compareTo(a.time!));
                  }
                });
              }),
          DataColumn(
            label: Container(
              width: 300,
              alignment: Alignment.center,
              child: Text(
                "通道名称",
                style: TextStyle(fontSize: 25),
              ),
            ),
          ),
          DataColumn(
            label: Container(
              width: 300,
              alignment: Alignment.center,
              child: Text(
                "设备MAC",
                style: TextStyle(fontSize: 25),
              ),
            ),
          ),
          DataColumn(
            label: Container(
              width: 300,
              alignment: Alignment.center,
              child: Text(
                "通行人员",
                style: TextStyle(fontSize: 25),
              ),
            ),
          ),
          DataColumn(
            label: Container(
              width: 300,
              alignment: Alignment.center,
              child: Text(
                "放行人员",
                style: TextStyle(fontSize: 25),
              ),
            ),
          ),
        ],
        source: OpenGateDataTableSource(widget.recordLists!),
      ),
    );
  }
}

class OpenGateDataTableSource extends DataTableSource {
  final List<GateRecordModel> data;

  OpenGateDataTableSource(this.data);

  @override
  DataRow? getRow(int index) {
    if (index >= data.length) {
      return null;
    }
    return DataRow.byIndex(
      index: index,
      selected: data[index].selected!,
      onSelectChanged: (selected) {
        data[index].selected = selected;
        notifyListeners();
      },
      cells: [
        DataCell(
          Container(
            // color: Colors.indigo,
            alignment: Alignment.center,
            child: data[index].controlType == 1
                ? Icon(
                    Icons.mic,
                    size: 30,
                  )
                : data[index].controlType == null
                    ? Icon(
                        Icons.fiber_manual_record_outlined,
                        size: 30,
                      )
                    : Icon(
                        Icons.fiber_manual_record_outlined,
                        size: 30,
                      ),
          ),
        ),
        DataCell(
          Container(
            width: 300,
            alignment: Alignment.center,
            // color: Colors.green,
            child: Text(
              "${data[index].time}",
              style: TextStyle(fontSize: 24),
            ),
          ),
        ),
        DataCell(
          Container(
            width: 300,
            alignment: Alignment.center,
            // color: Colors.yellow,
            child: Text(
              data[index].gateName == null
                  ? "无记录" //
                  : "${data[index].gateName}",
              style: TextStyle(fontSize: 24),
            ),
          ),
        ),
        DataCell(
          Container(
            width: 300,
            // color: Colors.greenAccent,
            alignment: Alignment.center,
            child: Text(
              "${data[index].gateMac}",
              style: TextStyle(fontSize: 24),
            ),
          ),
        ),
        DataCell(
          Container(
            width: 300,
            alignment: Alignment.center,
            // color: Colors.lightBlue,
            child: Text(
              "${data[index].passerby}",
              // "易烊千玺",
              style: TextStyle(fontSize: 24),
            ),
          ),
        ),
        DataCell(
          Container(
            width: 300,
            // color: Colors.yellow,
            alignment: Alignment.center,
            child: Text(
              "${data[index].operator}",

              /// "abcdefghijklmnopqrstuvwxyz",
              style: TextStyle(fontSize: 24),
            ),
          ),
        )
      ],
    );
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => data.length;

  @override
  int get selectedRowCount => 0;
}
